package com.example.onion.hxchat.room.repositorywc;

import android.content.Context;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import com.example.onion.hxchat.room.wcdatabase.MyDataBaseWc;
import com.example.onion.hxchat.room.entity.User;
import com.example.onion.hxchat.room.dao.UserDao;
import com.example.onion.hxchat.util.HttpUtils;

import java.util.List;

public class UserRepository {
    /**
     * Data list from Dao.
     */
    private LiveData<List<User>> users;

    private UserDao userDao;

    public UserRepository(Context context) {
        //获取数据库实例，数据库采用单例模式
        MyDataBaseWc database = MyDataBaseWc.getInstance(context.getApplicationContext());
        userDao = database.getUserDao();
        users = userDao.getAllUser();
    }

    /**
     * Gets all data from Master table from database.
     * @return The list of users
     */
    public LiveData<List<User>> getUsers() { return users; }


    public User getUserById(String id){
        return userDao.getUserById(id);
    }


    public void insertUsers(User... users){
        new UserRepository.InsertMasterAsyncTask(userDao).execute(users);
    }


    public void deleteAllUsers()
    {
        new DeleteAllUserAsyncTask(userDao).execute();
    }
    //内部类，用于在子线程中访问数据库，如果有多个操作的话，每一个操作都要对应一个AsyncTask
    static class InsertMasterAsyncTask extends AsyncTask<User,Void,Void> {

        private UserDao userDao;

        public InsertMasterAsyncTask(UserDao userDao) {
            this.userDao = userDao;
        }

        @Override
        protected Void doInBackground(User... users) {
            userDao.insertUser(users);
            return null;
        }
    }

    //内部类，用于在子线程中访问数据库，如果有多个操作的话，每一个操作都要对应一个AsyncTask

    static class DeleteAllUserAsyncTask extends AsyncTask<Void ,Void, Void> {

        private UserDao userDao;

        public DeleteAllUserAsyncTask(UserDao userDao) {
            this.userDao = userDao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            userDao.deleteAllUserS();
            return null;
        }
    }
}
